var fs = require('fs');
var path = require('path');
var express = require('express');
var gm = require('gm');
var index = require('../index');
var router = express.Router();

var PostModel = require('../models/posts');
var CommentModel = require('../models/comments');
var StudentModel = require('../models/students');
var checkLogin = require('../middlewares/check').checkLogin;

var uploadDir = path.join(__dirname, '../public/img/');
var oldPhotos = null;

// GET /posts 所有用户或者特定用户的文章页
//   eg: GET /posts?author=xxx
router.get('/', checkLogin, function(req, res, next) {
    var identity = req.session.user.identity;
    if ('教师' == identity || '管理员' == identity) {
        var author = req.query.author;

        PostModel.getPosts(author)
            .then(function (posts) {
                res.render('posts', {
                    posts: posts
                });
            })
            .catch(next);
    } else {
        res.redirect('/gallary');
    }
});

// GET /posts/create 发表文章页
router.get('/create', checkLogin, function(req, res, next) {
    StudentModel.getAllStudents()
        .then(function (students) {
            res.render('create', {
                students: students
            });
        })
        .catch(function (e) {
            next(e);
        });
    // res.render('create');
});

// POST /posts 发表一篇文章
router.post('/', checkLogin, function(req, res, next) {
    var author = req.session.user._id;
    var student_id = req.fields.student_id;
    var title = req.fields.title;
    var content = req.fields.content;
    var photos = req.files.photos.path.split(path.sep).pop();

    // 校验参数
    try {
        if (!title.length) {
            throw new Error('请填写标题');
        }
        if (!content.length) {
            throw new Error('请填写内容');
        }
        if (!req.files.photos.name) {
            // fs.unlink(req.files.photos.path);
            // photos = "";
            throw new Error('请上传图片');
        }
    } catch (e) {
        // 发布失败，删除上传的照片
        fs.unlink(req.files.photos.path);
        req.flash('error', e.message);
        return res.redirect('back');
    }

    var thumbs = 's_'+photos;
    // 生成缩略图 宽240，保持长宽比
    gm(uploadDir+photos).scale(240, 0, '^')
        .write(uploadDir+thumbs,
            function(err){console.log("err: " + err);});
    var post = {
        student_id: student_id,
        author: author,
        title: title,
        content: content,
        photos: photos,
        thumbs: thumbs,
        pv: 0
    };

    PostModel.create(post)
        .then(function (result) {
            // 此 post 是插入 mongodb 后的值，包含 _id
            post = result.ops[0];
            req.flash('success', '发表成功');
            // 发表成功后跳转到该文章页
            res.redirect(`/posts/${post._id}`);
        })
        .catch(function (e) {
            // 发布失败，删除上传的照片
            fs.unlink(req.files.photos.path);
            next(e);
        });
});

// GET /posts/:postId 单独一篇的文章页
router.get('/:postId', function(req, res, next) {
    var postId = req.params.postId;

    Promise.all([
        PostModel.getPostById(postId),// 获取文章信息
        CommentModel.getComments(postId),// 获取该文章所有留言
        PostModel.incPv(postId)// pv 加 1
    ])
        .then(function (result) {
            var post = result[0];
            var comments = result[1];
            if (!post) {
                throw new Error('该文章不存在');
            }

            res.render('post', {
                post: post,
                comments: comments
            });
        })
        .catch(next);
});

// GET /posts/:postId/edit 更新文章页
router.get('/:postId/edit', checkLogin, function(req, res, next) {
    var postId = req.params.postId;
    var author = req.session.user._id;

    PostModel.getRawPostById(postId)
        .then(function (post) {
            if (!post) {
                throw new Error('该文章不存在');
            }
            if (author.toString() !== post.author._id.toString()) {
                throw new Error('权限不足');
            }
            oldPhotos = post.photos; // keep old photo path to delete if needed
            res.render('edit', {
                post: post
            });
        })
        .catch(next);
});

// POST /posts/:postId/edit 更新一篇文章
router.post('/:postId/edit', checkLogin, function(req, res, next) {
    var postId = req.params.postId;
    var author = req.session.user._id;
    var title = req.fields.title;
    var content = req.fields.content;
    var photos = req.files.photos.path.split(path.sep).pop();

    // 校验参数
    try {
        if (!req.files.photos.name) {
            throw new Error('缺少图片');
        }
    } catch (e) {
        // 无效图片,异步删除上传的头像
        fs.unlink(req.files.photos.path);
        req.flash('error', e.message);
        return res.redirect('back');
    }

    // 删除旧的图片
    try {
        if (oldPhotos != null) {
            fs.unlink(uploadDir + oldPhotos);
        }
    } catch (e) {
        fs.unlink(req.files.photos.path);
        throw new Error(uploadDir + oldPhotos);
    }

    PostModel.updatePostById(postId, author, { title: title, content: content, photos: photos })
        .then(function () {
            req.flash('success', '编辑文章成功');
            // 编辑成功后跳转到上一页
            res.redirect(`/posts/${postId}`);
        })
        .catch(next);
});

// GET /posts/:postId/remove 删除一篇文章
router.get('/:postId/remove', checkLogin, function(req, res, next) {
    var postId = req.params.postId;
    var author = req.session.user._id;

    PostModel.delPostById(postId, author)
        .then(function () {
            req.flash('success', '删除文章成功');
            // 删除成功后跳转到主页
            res.redirect('/posts');
        })
        .catch(next);
});

// POST /posts/:postId/comment 创建一条留言
router.post('/:postId/comment', checkLogin, function(req, res, next) {
    var author = req.session.user._id;
    var postId = req.params.postId;
    var content = req.fields.content;
    var comment = {
        author: author,
        postId: postId,
        content: content
    };

    CommentModel.create(comment)
        .then(function () {
            req.flash('success', '留言成功');
            // 留言成功后跳转到上一页
            res.redirect('back');
        })
        .catch(next);
});

// GET /posts/:postId/comment/:commentId/remove 删除一条留言
router.get('/:postId/comment/:commentId/remove', checkLogin, function(req, res, next) {
    var commentId = req.params.commentId;
    var author = req.session.user._id;

    CommentModel.delCommentById(commentId, author)
        .then(function () {
            req.flash('success', '删除留言成功');
            // 删除成功后跳转到上一页
            res.redirect('back');
        })
        .catch(next);
});

module.exports = router;
